package net.form105.web.base.component.table;

import java.io.Serializable;
import java.util.Set;

import net.form105.web.base.model.CheckBoxModel;

import org.apache.wicket.Component;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
import org.apache.wicket.markup.IMarkupResourceStreamProvider;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.util.resource.IResourceStream;
import org.apache.wicket.util.resource.StringResourceStream;

/**
 * Checkbox column for {@link DataTable}
 *
 * @see CheckBoxModel
 * @author ivaynberg
 *
 */
public abstract class CheckBoxColumn extends AbstractColumn {
	private static final long serialVersionUID = 1L;
	private final IModel selectionModel;

	/**
	 * Constructor
	 * 
	 * @param selectionModel
	 *            model that represents a collection of selected tokens
	 *            generated by {@link #getModelObjectToken(IModel)}. Usually
	 *            this collection is a {@link Set} of primary keys.
	 */
	public CheckBoxColumn(IModel selectionModel) {
		super(selectionModel);
		this.selectionModel = selectionModel;
	}

	public void populateItem(Item cellItem, String componentId, IModel rowModel) {

		cellItem.add(new CheckBoxPanel(componentId, selectionModel, getModelObjectToken(rowModel)));
	}
	
	public Component getHeader(String componentId) {
		return new HeaderCheckBoxPanel("label");
	}

	/**
	 * Generates a token from the model object that will represent the selected
	 * state of this row. The implementation should usually return a primary key
	 * of the object inside the provided model.
	 * 
	 * Example: <code>return ((User)model.getObject()).getId();</code>
	 * 
	 * @param model
	 *            model that contains an object bound to current row of the
	 *            table
	 * @return a token which will uniquely identify the selection of this row
	 */
	protected abstract Serializable getModelObjectToken(IModel model);

	private static class CheckBoxPanel extends Panel implements IMarkupResourceStreamProvider {

		private static final long serialVersionUID = 1L;

		public CheckBoxPanel(String id, IModel model, Serializable token) {
			super(id, model);
			add(new CheckBox("checkbox", new CheckBoxModel(model, token)));
		}

		public IResourceStream getMarkupResourceStream(final MarkupContainer container, Class containerClass) {
			return new StringResourceStream(
					"<wicket:panel><input wicket:id=\"checkbox\" type=\"checkbox\"/></wicket:panel>");
		}
	}

}
